<script setup lang='ts'>
// import type { FieldValues } from 'plus-pro-components'
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'

import { getAllCity, getDetail, useAdgroupDel, useAdgroupList, useAdgroupSave, useAdgroupSwitchStatus, useAdgroupUpdate, useGetDictData } from '@fl/api/advertising-api'
import { SearchForm, SearchTable } from '@fl/components'
import { cloneDeep } from 'lodash-es'

import type { cityType } from './type'

import advertisingConfig from './components/advertising-config.vue'
import { adgDialogTag } from './type'

const route = useRoute()

const initialState = {
    activeStatus: undefined,
    name: '',
}
const state = ref(cloneDeep(initialState))

watch(
    () => route.query.keyword,
    (newKeyword) => {
        state.value = {
            ...initialState,
            name: newKeyword as string || '',
        }
    },
    {
        immediate: true,
    },
)

const initialPage = {
    currentPage: 1,
    pageSize: 10,
    total: 0,
}
const tablePage = ref(cloneDeep(initialPage))

const columns = [
    {
        colProps: {
            span: 6,
        },
        label: '搜索关键词',
        prop: 'name',
        valueType: 'copy',
    },
    {
        colProps: {
            span: 6,
        },
        label: '活动状态',
        options: [
            {
                label: '未开始',
                value: '0',
            },
            {
                label: '进行中',
                value: '1',
            },
        ],
        prop: 'activeStatus',
        valueType: 'select',
    },

]

const dialogTitle = ref('')
const formRef = ref()
const initState = {
    city: [],
    device: [],
    deviceId: '',
    id: undefined,
    name: '',
    platform: [],
    regionType: '',
    version: '',
}

const dialogVisible = ref(false)
const dialogWidth = ref(666)
const form = ref()

onMounted(() => {
    if (route.query.id) {
        groupId.value = Number(route.query.id)
        dialogWidth.value = 1060
        dialogTitle.value = adgDialogTag.ADVERTISING_CONFIG
        dialogVisible.value = true
    }
})

const formRule = {
    device: [
        {
            message: '请输入机型渠道',
            required: true,
            trigger: 'blur',
        },
    ],
    name: [
        {
            message: '请输入广告名称',
            required: true,
            trigger: 'blur',
        },
    ],
    platform: [
        {
            message: '请选择平台类型',
            required: true,
            trigger: 'blur',
        },
    ],
    regionType: [
        {
            message: '请选择',
            required: true,
            trigger: 'blur',
        },
    ],
    version: [
        {
            message: '请输入版本',
            required: true,
            trigger: 'blur',
        },
    ],
}
const formColumns = ref(cloneDeep([
    {
        label: '广告组名称',
        labelWidth: 100,
        prop: 'name',
    },
    {
        fieldProps: {
            filterable: true,
            multiple: true,
        },
        label: '平台类型',
        labelWidth: 100,
        options: [],
        prop: 'platform',
        valueType: 'select',
    },
    {
        fieldProps: {
            filterable: true,
            multiple: true,
        },
        label: '城市',
        labelWidth: 100,
        options: [],
        prop: 'city',
        valueType: 'select',
    },
    {
        label: '版本',
        labelWidth: 100,
        prop: 'version',
    },
    {
        fieldProps: {
            filterable: true,
            multiple: true,
        },
        label: '机型渠道',
        labelWidth: 100,
        options: [],
        prop: 'device',
        valueType: 'select',
    },
    {
        fieldProps: {
            filterable: true,
        },
        label: '区域',
        labelWidth: 100,
        options: [],
        prop: 'regionType',
        valueType: 'select',
    },
    {
        fieldProps: {
            filterable: true,
            multiple: true,
        },
        label: '手机识别码',
        labelWidth: 100,
        prop: 'deviceId',
    },
    {
        label: '备注',
        labelWidth: 100,
        prop: 'remark',
        valueType: 'textarea',
    },
],
))
const gridOptions = reactive<VxeGridProps>({
    columns: [
        { field: 'name', title: '广告名称' },
        { field: 'contentQuantity', title: '分期内容数量', width: 110 },
        { field: 'platform', title: '平台类型' },
        { field: 'regionType', title: '区域' },
        { field: 'createTime', title: '创建时间' },
        { field: 'creator', title: '操作人' },
        { field: 'remark', title: '备注' },
        { field: 'activeStatus', slots: { default: 'activeStatus' }, title: '启用/禁用', width: 100 },
        { fixed: 'right', slots: { default: 'operate' }, title: '操作', width: 210 },
    ],
})
const list = ref([])
const params = computed(() => ({
    pageNum: tablePage.value.currentPage,
    pageSize: tablePage.value.pageSize,
    ...state.value,
}))
const groupId = ref() // 广告组id

const { data, isLoading, refetch } = useAdgroupList(params)
const { data: dictList } = useGetDictData({ dictType: 'device,platform,advertisement_region_type' })
const { isPending, mutate } = useAdgroupSave()
const { mutate: mutateUpdate } = useAdgroupUpdate()
const { mutate: mutateDel } = useAdgroupDel()
const { mutate: mutateSwitch } = useAdgroupSwitchStatus()

watchEffect(() => {
    if (data.value) {
        list.value = cloneDeep(data.value.rows).reduce((pre, cur) => {
            cur.activeStatus = cur.activeStatus === 1 ? 1 : 0
            pre.push(cur)
            return pre
        }, [])
        tablePage.value.total = data.value.total!
        // console.log('list.value', list.value)
    }
    if (dictList.value) {
        formColumns.value[1].options = dictList.value.platform
        formColumns.value[4].options = dictList.value.device
        formColumns.value[5].options = dictList.value.advertisement_region_type
    }
})

function getCityList() {
    getAllCity().then((res: any) => {
        if (res.code === 200) {
            if (res.data) {
                formColumns.value[2].options = res.data.reduce((pre: any, cur: any) => {
                    cur.label = cur.areaName
                    cur.value = cur.areaCode
                    pre.push(cur)
                    return pre
                }, [])
                // console.log(666, formColumns.value[2].options)
            }
        }
    }).catch((error) => {
        ElMessage.error(error.msg)
    })
}

/**
 * methods start
 */

// function submitSearch(values: FieldValues) {
function submitSearch(values) {
    state.value = cloneDeep(values)
    tablePage.value.currentPage = 1
}

function resetSearch() {
    state.value = cloneDeep(initialState)
    tablePage.value = cloneDeep(initialPage)
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
}

// 新增广告
async function addAdertisingGroup() {
    dialogTitle.value = adgDialogTag.ADD_ADVERTISING_GROUP
    form.value = cloneDeep(initState)
    dialogVisible.value = true
}

// 提交新增/编辑/复制广告组
function adGroupSubmit(values) {
    let city
    if (values.city?.length) {
        const cityList = formColumns.value[2].options || []
        city = cityList.filter((item: cityType) => values.city.includes(item.areaCode)).map((val: cityType) => val.areaName).join(',')
    }
    const platform = values.platform.join(',')
    const device = values.device?.join(',')
    const areaId = values.city?.join(',')
    const regionType = values.regionType
    const params = {
        ...values,
        areaId,
        city,
        device,
        platform,
        regionType,
    }
    switch (dialogTitle.value) {
        case '新增广告组':
        case '复制广告组':
            mutate(params, {
                onSuccess: () => {
                    ElMessage.success('新增成功')
                    dialogVisible.value = false
                },
            })
            break
        case '编辑广告组':
            mutateUpdate(params, {
                onSuccess: () => {
                    ElMessage.success(dialogTitle.value === adgDialogTag.EDIT_ADVERTISING_GROUP ? '编辑成功' : '复制成功')
                    dialogVisible.value = false
                },
            })
            break
    }
}

// 编辑/复制广告组
async function setAdgroup(row, title) {
    dialogTitle.value = title
    getDetail({
        id: row.id,
    }).then((data) => {
        const { areaId, device, deviceId, id, name, platform, remark, version, regionType } = data
        const newPlatform = (platform && platform.split(',')) || []
        const newCity = areaId ? areaId.split(',').map(String) : []
        const newDevice = device ? device.split(',') : []
        form.value = {
            city: newCity,
            device: newDevice,
            deviceId,
            id,
            name,
            platform: newPlatform,
            remark,
            version,
            regionType,
        }
        if (title === adgDialogTag.COPY_ADVERTISING_GROUP) {
            form.value.name += '副本'
            form.value.copyId = id
            delete form.value.id
        }

        dialogVisible.value = true
    })
}

// 配置广告
function adConfig(row, title) {
    groupId.value = row.id
    dialogWidth.value = 1060
    dialogTitle.value = title
    dialogVisible.value = true
}

// 删除广告组
function delAdgroup(row) {
    const { id, name } = row
    ElMessageBox.confirm(
        `你确实要删除广告组『${name}』吗？`,
        '删除',
        {
            cancelButtonText: '取消',
            confirmButtonText: '删除',
            type: 'warning',
        },
    )
        .then(() => {
            mutateDel({
                id,
            }, {
                onSuccess: () => {
                    ElMessage.success('删除成功')
                },
            })
        }).catch(() => {
            ElMessage({
                message: '取消删除',
                type: 'info',
            })
        })
}

function closeDialog() {
    dialogVisible.value = false
    // 这是为了让每次打开弹窗都会重新渲染，不然会出现弹窗内容为上一次打开的内容
    dialogTitle.value = ''
}

function closeAndRefresh() {
    closeDialog()
    refetch()
}

// 启用禁用
function switchActiveStatus(row) {
    const params = {
        enable: row.activeStatus,
        id: row.id,
    }
    mutateSwitch(params, {
        onError() {
            setTimeout(() => {
                row.activeStatus = row.activeStatus === 1 ? 0 : 1
            }, 500)
        },
        onSuccess: (res) => {
            // console.log('res', res)
            const tips = row.activeStatus === 1 ? '已启用' : '已禁用'
            ElMessage({
                message: tips,
                type: row.activeStatus === 1 ? 'success' : 'info',
            })
        },
    })
}

/**
 * methods end
 */

onMounted(() => {
    getCityList()
})
</script>

<template>
    <div class="advertising-group">
        <div class="advertising-group-list">
            <ElCard class="mb-20"
                    shadow="never"
            >
                <SearchForm v-model="state"
                            :columns="columns"
                            submit-text="搜索"
                            @reset="resetSearch"
                            @submit="submitSearch"
                />
            </ElCard>

            <ElCard shadow="never">
                <SearchTable v-bind="gridOptions"
                             v-model:pager="tablePage"
                             :loading="isLoading"
                             :data="list"
                             @page-change="handlePageChange"
                >
                    <template #toolbar_buttons>
                        <el-button plain
                                   type="primary"
                                   @click="addAdertisingGroup"
                        >
                            新增广告组
                        </el-button>
                    </template>

                    <!-- <template #activeStatus="row">
                        <div class="status"
                             :class="[`status-${row.row.activeStatus}`,

                             ]"
                        >
                            {{ ['未开始', '进行中', '已结束'][row.row.activeStatus] }}
                        </div>
                    </template> -->
                    <template #activeStatus="{ row }">
                        <el-switch v-model="row.activeStatus"
                                   :active-value="1"
                                   :inactive-value="0"
                                   @change="switchActiveStatus(row)"
                        />
                    </template>

                    <template #operate="{ row }">
                        <div class="operate-btns">
                            <el-button type="primary"
                                       text
                                       @click="setAdgroup(row, adgDialogTag.EDIT_ADVERTISING_GROUP)"
                            >
                                编辑
                            </el-button>

                            <el-button type="primary"
                                       text
                                       @click="adConfig(row, adgDialogTag.ADVERTISING_CONFIG)"
                            >
                                配置广告
                            </el-button>

                            <el-button type="info"
                                       text
                                       @click="setAdgroup(row, adgDialogTag.COPY_ADVERTISING_GROUP)"
                            >
                                复制
                            </el-button>

                            <el-button type="info"
                                       text
                                       @click="delAdgroup(row)"
                            >
                                删除
                            </el-button>
                        </div>
                    </template>
                </SearchTable>
            </ElCard>
        </div>

        <el-dialog v-model="dialogVisible"
                   :close-on-click-modal="false"
                   :close-on-press-escape="false"
                   :title="dialogTitle"
                   :width="dialogWidth"
                   :class="[adgDialogTag.SELECT_MATERIAL].includes(dialogTitle) ? 'ad-config-dialog' : ''"
                   @closed="closeDialog"
        >
            <template #header>
                <h3 class="dialog-title">
                    {{ dialogTitle }}
                    <span v-if="dialogTitle === adgDialogTag.ADVERTISING_CONFIG"
                          class="mark"
                    >（更改广告组数据后，所有引用该广告组的页面均会自动更新为最新版数据）</span>
                </h3>
            </template>
            <!-- 新增/编辑/复制广告组 -->
            <template v-if="[adgDialogTag.ADD_ADVERTISING_GROUP, adgDialogTag.EDIT_ADVERTISING_GROUP, adgDialogTag.COPY_ADVERTISING_GROUP].includes(dialogTitle)">
                <PlusForm ref="formRef"
                          v-model="form"
                          :columns="formColumns"
                          :rules="formRule"
                          :submit-loading="isPending"
                          @submit="adGroupSubmit"
                >
                    <template #footer="{ handleSubmit, handleReset }">
                        <div class="form-btn">
                            <el-button type="primary"
                                       :loading="isPending"
                                       @click="handleSubmit"
                            >
                                提交
                            </el-button>

                            <el-button plain
                                       @click="handleReset"
                            >
                                重置
                            </el-button>
                        </div>
                    </template>
                </PlusForm>
            </template>
            <!-- 广告配置 -->
            <template v-if="dialogTitle === adgDialogTag.ADVERTISING_CONFIG">
                <advertising-config v-model="groupId"
                                    @close-and-refresh="closeAndRefresh"
                />
            </template>
        </el-dialog>
    </div>
</template>

<style lang="scss" scoped>
:deep(.el-tabs__nav-wrap::after) {
    height: 0;
}

:deep(.operate-btns .el-button) {
    margin: 0;
    padding: 6px;
}

.form-btn {
    display: flex;
    justify-content: flex-end;
    width: 100%;
}

.status {
    width: 52px;
    height: 24px;
    border-radius: 2px;
    line-height: 24px;
    text-align: center;
    font-size: 12px;
    margin: 0 auto;

    &.status-0 {
        background-color: #fff8f0;
        color: #e9810b;
    }

    &.status-1 {
        background-color: #f0fff0;
        color: #18b918;
    }

    &.status-2 {
        background-color: #f2f3f5;
        color: #86909c;
    }
}
</style>

<style lang="scss">
.ad-config-dialog {
    height: 88% !important;

    .el-dialog__body {
        height: 80%;
        overflow-y: auto;
    }
}

.dialog-title {
    font-size: 18px;

    > .mark {
        font-size: 14px;
        color: #4e5969;
    }
}

.advertising-group {
    .ad-by-stages {
        display: flex;
        flex-wrap: wrap;

        .time-item {
            display: flex;
            width: 310px;
            margin-bottom: 12px;

            .ad-time-piker {
                display: flex;
                align-items: center;
                position: relative;

                > .sort {
                    position: absolute;
                    left: 0;
                    top: 0;
                    width: 30px;
                    height: 32px;
                    display: block;
                    font-size: 16px;
                    line-height: 32px;
                    border-right: 1px solid #e6ebf5;
                    text-align: center;
                    cursor: pointer;

                    &.active {
                        color: var(--el-color-primary);
                        border-right: 1px solid var(--el-color-primary);
                    }
                }

                &.active {
                    .el-range-editor.el-input__wrapper {
                        border: 1px solid var(--el-color-primary);
                    }
                }
            }

            .el-range-editor.el-input__wrapper {
                width: 260px;
                padding-left: 40px;
            }

            .icon-btns {
                display: flex;
                align-items: center;
                margin-left: 10px;

                .el-icon {
                    font-size: 18px;
                    cursor: pointer;

                    &.add {
                        color: var(--el-color-primary);
                        margin-right: 6px;
                    }
                }
            }
        }
    }
}
</style>
